package core;

import java.util.ArrayList;
import java.util.List;

public class ReversiBoard extends Board {
    public ReversiBoard(String player1Name, String player2Name) {
        super(player1Name, player2Name);
    }

    @Override
    protected void initializeBoard() {
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                grid[i][j] = EMPTY;
            }
        }


        grid[3][3] = WHITE;
        grid[3][4] = BLACK;
        grid[4][3] = BLACK;
        grid[4][4] = WHITE;
    }

    @Override
    public boolean makeMove(int row, int col) {
        if (gameOver || !isValidPosition(row, col) || grid[row][col] != EMPTY) {
            return false;
        }

        char currentPiece = currentPlayer.getPiece();
        char opponentPiece = (currentPiece == BLACK) ? WHITE : BLACK;
        boolean validMove = false;

        // 检查8个方向
        for (int dx = -1; dx <= 1; dx++) {
            for (int dy = -1; dy <= 1; dy++) {
                if (dx == 0 && dy == 0) continue;

                if (checkDirection(row, col, dx, dy, currentPiece, opponentPiece)) {
                    validMove = true;
                    flipPieces(row, col, dx, dy, currentPiece, opponentPiece);
                }
            }
        }

        if (validMove) {
            grid[row][col] = currentPiece;

            // 检查游戏是否结束
            checkGameOver();

            if (!gameOver) {
                switchPlayer();

                // 检查新玩家是否有合法移动，如果没有则跳过
                if (getLegalMoves(currentPlayer).isEmpty()) {
                    System.out.println(currentPlayer.getName() + "没有合法落子位置，跳过回合");
                    switchPlayer();

                    // 如果双方都没有合法移动，游戏结束
                    if (getLegalMoves(currentPlayer).isEmpty()) {
                        gameOver = true;
                    }
                }
            }

            return true;
        }

        return false;
    }

    public void pass() {
        if (getLegalMoves(currentPlayer).isEmpty()) {
            switchPlayer();

            // 检查新玩家是否有合法移动，如果没有则游戏结束
            if (getLegalMoves(currentPlayer).isEmpty()) {
                gameOver = true;
            }
        } else {
            System.out.println("当前有合法落子位置，不能pass！");
        }
    }

    @Override
    public void display() {
        System.out.println("  A B C D E F G H");
        System.out.println("  -----------------");

        List<int[]> legalMoves = getLegalMoves(currentPlayer);

        for (int i = 0; i < 8; i++) {
            System.out.print((i + 1) + " |");
            for (int j = 0; j < 8; j++) {
                // 显示合法落子位置
                boolean isLegalMove = false;
                for (int[] move : legalMoves) {
                    if (move[0] == i && move[1] == j) {
                        isLegalMove = true;
                        break;
                    }
                }

                if (isLegalMove) {
                    System.out.print(LEGAL_MOVE + " ");
                } else {
                    System.out.print(grid[i][j] + " ");
                }
            }
            System.out.print("|");

            // 显示玩家信息和分数
            if (i == 2) {
                System.out.print("  游戏 " + (GameManager.getCurrentGameIndex() + 1));
            } else if (i == 3) {
                int blackCount = countPieces(BLACK);
                System.out.print("  " + player1.getName() +
                        (currentPlayer == player1 ? " " + BLACK : "") +
                        "  " + blackCount);
            } else if (i == 4) {
                int whiteCount = countPieces(WHITE);
                System.out.print("  " + player2.getName() +
                        (currentPlayer == player2 ? " " + WHITE : "") +
                        "  " + whiteCount);
            } else if (i == 6 && gameOver) {
                System.out.print("  游戏结束");
            } else if (i == 7 && gameOver) {
                int blackCount = countPieces(BLACK);
                int whiteCount = countPieces(WHITE);
                if (blackCount > whiteCount) {
                    System.out.print("  " + player1.getName() + " 获胜");
                } else if (whiteCount > blackCount) {
                    System.out.print("  " + player2.getName() + " 获胜");
                } else {
                    System.out.print("  平局");
                }
            }

            System.out.println();
        }
        System.out.println("  -----------------");
    }

    @Override
    protected List<int[]> getLegalMoves(Player player) {
        List<int[]> moves = new ArrayList<>();
        char currentPiece = player.getPiece();
        char opponentPiece = (currentPiece == BLACK) ? WHITE : BLACK;

        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if (grid[i][j] == EMPTY) {
                    // 检查8个方向
                    for (int dx = -1; dx <= 1; dx++) {
                        for (int dy = -1; dy <= 1; dy++) {
                            if (dx == 0 && dy == 0) continue;

                            if (checkDirection(i, j, dx, dy, currentPiece, opponentPiece)) {
                                moves.add(new int[]{i, j});
                                break; // 只要有一个方向合法即可
                            }
                        }
                    }
                }
            }
        }

        return moves;
    }

    private boolean checkDirection(int row, int col, int dx, int dy,
                                   char currentPiece, char opponentPiece) {
        int x = row + dx;
        int y = col + dy;
        boolean foundOpponent = false;

        while (isValidPosition(x, y)) {
            if (grid[x][y] == opponentPiece) {
                foundOpponent = true;
                x += dx;
                y += dy;
            } else if (grid[x][y] == currentPiece && foundOpponent) {
                return true;
            } else {
                break;
            }
        }

        return false;
    }

    private void flipPieces(int row, int col, int dx, int dy,
                            char currentPiece, char opponentPiece) {
        int x = row + dx;
        int y = col + dy;

        while (isValidPosition(x, y) && grid[x][y] == opponentPiece) {
            grid[x][y] = currentPiece;
            x += dx;
            y += dy;
        }
    }

    private void checkGameOver() {
        // 棋盘已满
        if (isBoardFull()) {
            gameOver = true;
            return;
        }

        // 双方都没有合法移动
        if (getLegalMoves(currentPlayer).isEmpty()) {
            Player nextPlayer = (currentPlayer == player1) ? player2 : player1;
            if (getLegalMoves(nextPlayer).isEmpty()) {
                gameOver = true;
            }
        }
    }

    private boolean isBoardFull() {
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if (grid[i][j] == EMPTY) {
                    return false;
                }
            }
        }
        return true;
    }

    private int countPieces(char piece) {
        int count = 0;
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if (grid[i][j] == piece) {
                    count++;
                }
            }
        }
        return count;
    }
}